package org.adultedu.controller;

import org.adultedu.pojo.Course;
import org.adultedu.pojo.Ctype;
import org.adultedu.pojo.TcList;
import org.adultedu.result.Result;
import org.adultedu.result.ResultEnum;
import org.adultedu.result.ResultUtil;
import org.adultedu.service.CourseService;
import org.adultedu.service.CtypeService;
import org.adultedu.service.TcListService;
import org.adultedu.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
public class CourseController {
    @Autowired
    private CourseService courseService;
    @Autowired
    private CtypeService ctypeService;
    @Autowired
    private TcListService tcListService;

    @GetMapping(value = "/querylimitcourse")
    public Result queryLimitCourse(String cname,String level,String cway,Integer currentpage,Integer pagesize){
        List list;
        System.out.println(cname+level+cway+currentpage+pagesize+"ok");
        currentpage = (currentpage-1)*pagesize;
        list = courseService.queryUniqueCourse(cname,null,null,level,cway,currentpage,pagesize);
        System.out.println(list);
        return ResultUtil.success(list);
    }

    @GetMapping(value = "/queryteachercourse")
    public Result queryTeacherCourse(String tid){
        List list;
        list = courseService.queryTeacherCourse(tid);
        System.out.println(list);
        if(!list.isEmpty()){
            return ResultUtil.success(list,list.size());
        }else {
            return ResultUtil.error(ResultEnum.DATA_IS_NULL.getCode(),ResultEnum.DATA_IS_NULL.getMsg());
        }

    }

    @GetMapping(value = "/getsalespreview")
    public Result getSalesPreview(String tid){
        List list = courseService.getSalesPreview(tid);
        if(!list.isEmpty()){
            return ResultUtil.success(list);
        }else {
            return ResultUtil.error(ResultEnum.DATA_IS_NULL.getCode(),ResultEnum.DATA_IS_NULL.getMsg());
        }

    }

    @GetMapping(value = "/querycourse")
    public Result queryCourse(String cname,String level,String cway){
        List list;
        list = courseService.queryCourse(cname,null,null,level,cway);
        if(!list.isEmpty()){
            return ResultUtil.success(list);
        }else {
            return ResultUtil.error(ResultEnum.DATA_IS_NULL.getCode(),ResultEnum.DATA_IS_NULL.getMsg());
        }
    }

    @GetMapping(value = "/getStudentCourse")
    public Result getStudentCourse(String sid){
        List list;
        list = courseService.getStudentCourse(sid);
        if(!list.isEmpty()){
            return ResultUtil.success(list);
        }else {
            return ResultUtil.error(ResultEnum.DATA_IS_NULL.getCode(),ResultEnum.DATA_IS_NULL.getMsg());
        }
    }

    @GetMapping(value = "/getpagenum")
    public Result getPageNum(String tid,String cname,String level,String cway,Integer pagesize){
        Integer num = courseService.queryCoursePage(cname,null,null,level,cway);
        //num = (num-1+pagesize)/pagesize;
        return ResultUtil.success(num);
    }

    @RequestMapping(value = "/updatecourse",method = RequestMethod.POST)
    public Result updateCourse(@RequestBody Map<String,String> map){
        Course course = new Course();
        Ctype ctype = new Ctype();
        map.remove("edit");
        //System.out.println(map);
        course.setCid(map.get("cid"));
        course.setCname(map.get("cname"));
        course.setCnum(Integer.parseInt(map.get("cnum")));
        course.setChour(Integer.parseInt(map.get("chour")));
        course.setCvalue(Integer.parseInt(map.get("cvalue")));
        ctype.setCid(map.get("cid"));
        ctype.setCway(map.get("cway"));
        ctype.setLevel(map.get("level"));
        if(courseService.updateCourse(course)==1 && ctypeService.updateCtype(ctype) == 1){
            return ResultUtil.success();
        }
        else {
            return ResultUtil.error(ResultEnum.UPDATE_FAIL.getCode(),ResultEnum.UPDATE_FAIL.getMsg());
        }
    }
    @GetMapping(value = "/insertPic")
    public void insertPic(String url,String cid){
        System.out.println(url);
        courseService.updatePic(url,cid);
    }
    @GetMapping(value = "/deletecourse")
    public Result deleteCourse(String cid){
        if(courseService.deleteCourse(cid) ==1 ){
            return ResultUtil.success();
        } else{
            return ResultUtil.error(ResultEnum.DELETE_FAIL.getCode(),ResultEnum.DELETE_FAIL.getMsg());
        }
    }

    @RequestMapping(value = "/verifycourse",method = RequestMethod.POST)
    public Result verifyCourse(@RequestBody Map<String,String> map){
        TcList tcList = new TcList(map.get("cid"),null,null,1);
        if(tcListService.updateTcList(tcList) == 1){
            return ResultUtil.success();
        } else{
            return ResultUtil.error(ResultEnum.UPDATE_FAIL.getCode(),ResultEnum.UPDATE_FAIL.getMsg());
        }
    }

    @RequestMapping(value = "/uploadImage")
    public String megerUserShopImg(MultipartFile file) {
        //判断所上传文件是否存在
        if (file.isEmpty()) {
            return "上传错误";
        }
        //获取上传文件的原始名称
        String originalFilename = file.getOriginalFilename();
        //设置上传文件的保存地址目录
        String dirPath = "D:/AdultEdu/CourseHead/";
        File filePath = new File(dirPath);
        //如果保存的地址不存在,就先创建目录
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        //获取当前文件的后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //使用UUID重新命名上传的文件名称(UUID(唯一识别码)+原始文件名称后缀)
        String newFileName = UUIDUtils.generateShortUuid() + "." + suffix;
        try {
            //创建可能会有错误,强制添加异常
            file.transferTo(new File(dirPath + newFileName));
        } catch (IOException e) {
            e.printStackTrace();
            return "上传错误";
        }
        System.out.println(dirPath + newFileName);
        return "http://localhost:8080/CourseHead/"+newFileName;
    }

    @RequestMapping(value = "/insertcourse",method = RequestMethod.POST)
    public Result insertCourse(@RequestBody Map[] course) throws ParseException {
        int flag = 0;
        int length = course.length;
        for(int i = 0;i<course.length;i++) {
            String uuid = UUIDUtils.generateShortUuid();
            course[i].put("id",uuid);
            course[i].put("level",course[i].get("level").toString());
            course[i].put("cway",course[i].get("cway").toString());
            course[i].put("cnum",Integer.parseInt((String)course[i].get("cnum")));
            course[i].put("cvalue",Integer.parseInt((String)course[i].get("cvalue")));
        }
        for(int i = 0;i<course.length;i++) {
            courseService.insertCourse(course[i]);
            ctypeService.insertCtypeByMap(course[i]);
            tcListService.insertTcList(course[i]);
            flag++;
        }

        if(flag== length){
            return ResultUtil.success();
        }else {
            return ResultUtil.error(ResultEnum.INSERT_FAIL.getCode(),ResultEnum.INSERT_FAIL.getMsg());
        }

    }

    @GetMapping("/deleteCoursePic")
    public Result deleteCoursePic(String cid,String url){
        String dirPath = "D:/AdultEdu/CourseHead/";
        String name = url.substring(33);
        String dir = dirPath+name;
        System.out.println(dir);
        File deleteFile = new File(dir);
        if(deleteFile.exists()){
            deleteFile.delete();
            courseService.updatePic("",cid);
            return ResultUtil.success();
        }else{
            return ResultUtil.error(404,"文件地址错误");
        }
    }

}
